using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Application.Dtos;
using UniversalAdmin.Application.Dtos.ArticleCategory;
using UniversalAdmin.Application.Services.Interfaces;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ArticleCategoryController : ControllerBase
{
    private readonly IArticleCategoryService _categoryService;

    public ArticleCategoryController(IArticleCategoryService categoryService)
    {
        _categoryService = categoryService;
    }

    /// <summary>
    /// 获取所有分类列表（分页查询）
    /// </summary>
    /// <param name="pageRequestDto">分页查询参数</param>
    /// <returns>分页分类列表</returns>
    [HttpGet]
    public async Task<IActionResult> GetAllCategories([FromQuery] PageRequestDto pageRequestDto)
    {
        var categories = await _categoryService.GetPagedAsync(pageRequestDto);
        return Ok(categories);
    }

    /// <summary>
    /// 根据ID获取分类详情
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    /// <returns>分类详情</returns>
    [HttpGet("{categoryId}")]
    public async Task<IActionResult> GetCategoryById(Guid categoryId)
    {
        var category = await _categoryService.GetByIdAsync(categoryId);
        if (category == null)
            return NotFound("未找到分类");
        return Ok(category);
    }

    /// <summary>
    /// 获取分类树形结构
    /// </summary>
    /// <returns>分类树</returns>
    [HttpGet("tree")]
    public async Task<IActionResult> GetCategoryTree()
    {
        var tree = await _categoryService.GetTreeAsync();
        return Ok(tree);
    }

    /// <summary>
    /// 获取子分类列表
    /// </summary>
    /// <param name="parentId">父分类ID</param>
    /// <returns>子分类列表</returns>
    [HttpGet("children")]
    public async Task<IActionResult> GetChildrenCategories([FromQuery] Guid? parentId)
    {
        var children = await _categoryService.GetChildrenAsync(parentId);
        return Ok(children);
    }

    /// <summary>
    /// 创建新分类
    /// </summary>
    /// <param name="createCategoryDto">分类创建参数</param>
    /// <returns>创建结果</returns>
    [HttpPost]
    public async Task<IActionResult> CreateCategory([FromBody] CreateArticleCategoryDto createCategoryDto)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        try
        {
            var category = await _categoryService.CreateAsync(createCategoryDto);
            return CreatedAtAction(nameof(GetCategoryById), new { categoryId = category.Id }, category);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 更新分类信息
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    /// <param name="updateCategoryDto">分类更新参数</param>
    /// <returns>更新结果</returns>
    [HttpPut("{categoryId}")]
    public async Task<IActionResult> UpdateCategory(Guid categoryId, [FromBody] UpdateArticleCategoryDto updateCategoryDto)
    {
        if (categoryId != updateCategoryDto.Id)
            return BadRequest("ID 不匹配");

        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        try
        {
            var category = await _categoryService.UpdateAsync(updateCategoryDto);
            return Ok(category);
        }
        catch (ArgumentException ex)
        {
            return NotFound(ex.Message);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 删除分类（软删除）
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{categoryId}")]
    public async Task<IActionResult> DeleteCategory(Guid categoryId)
    {
        try
        {
            await _categoryService.DeleteAsync(categoryId);
            return Ok("分类删除成功");
        }
        // 当传入的 categoryId 找不到对应的分类时抛出，返回 404 Not Found
        catch (ArgumentException)
        {
            return NotFound("分类Id不存在");
        }
        // 当分类无法删除时抛出（比如分类下还有子分类或关联的文章），返回 400 Bad Request
        catch (InvalidOperationException)
        {
            return BadRequest("分类下还有子分类或关联的文章，无法删除");
        }
        catch (Exception)
        {
            return BadRequest("删除分类时发生错误");
        }
    }

    /// <summary>
    /// 检查分类是否有子分类
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    /// <returns>是否有子分类</returns>
    [HttpGet("{categoryId}/has-children")]
    public async Task<IActionResult> HasChildren(Guid categoryId)
    {
        var hasChildren = await _categoryService.HasChildrenAsync(categoryId);
        return Ok(hasChildren);
    }

    /// <summary>
    /// 检查分类是否有文章
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    /// <returns>是否有文章</returns>
    [HttpGet("{categoryId}/has-articles")]
    public async Task<IActionResult> HasArticles(Guid categoryId)
    {
        var hasArticles = await _categoryService.HasArticlesAsync(categoryId);
        return Ok(hasArticles);
    }
}
